package com.example.SpringBootDemo.controller;

import com.example.SpringBootDemo.model.Person;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RequestMapping("/Spring")
@RestController
public class RequestController {
    // 传递字符串
    @RequestMapping("/m1")
    public String m1(String name) {
        return "name: " + name;
    }
    // 传递字符串 + 整型  这里不建议使用int 因为int 无法区分 null 和 0
    @RequestMapping("/m2")
    public String m2(String name,Integer age) {
        return "name: " + name + ",age: " + age;
    }
    // 传递对象
    @RequestMapping("/m3")
    public String m3(Person person) {
        System.out.println(person.toString());
        return person.toString();
    }
    // 参数重命名, 但是这里是不为空的, 如果不传递 name 就会报错
    @RequestMapping("/m4")
    public String m4(@RequestParam("name") String userName) {
        return "userName: " + userName;
    }
    // 这里是将true 改成 false, name就可以 不传递了
    @RequestMapping("/m5")
    public String m5(@RequestParam(value = "name",required = false) String userName) {
        return "userName: " + userName;
    }
    // 请求 127.0.0.1:8080/Spring/m6?name=zhangsan,name=lisi,name=zhaoliu
    // 127.0.0.1:8080/Spring/m6?name=zhangsan&name=lisi&name=zhaoliu
    // 传递数组
    @RequestMapping("/m6")
    public String m6(String[] name) {
        return "接收到的arrayParam: " + Arrays.toString(name) + " arrayParam长度: " + name.length;
    }

    @RequestMapping("/m7")
    public String m7(@RequestParam List<String> listParam) {
        return "接收到的arrayParam: " +listParam + " arrayParam长度: " + listParam.size();
    }
    // 传递json
//    {
//        "name":"zhangsan",
//            "age":18,
//            "id":2000
//    }
    @RequestMapping("/m8")
    public String m8(@RequestBody Person person) {
        return person.toString();
    }

    // 传递json 和获取 url中的值
    //127.0.0.1:8080/Spring/m9/zhangsan/9
    @RequestMapping("/m9/{nameId}/{ageId}")
    public String m9(@PathVariable String nameId, @PathVariable Integer ageId,@RequestBody Person person) {
        return "nameId: " + nameId + ", ageId: " + ageId + "  接收到的person: " + person.toString();
    }
    // 上传图片
    //
    @RequestMapping("/m10")
    public String m10(@RequestPart MultipartFile file) throws IOException {
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("D:/text/" + file.getOriginalFilename()));
        return "success";
    }
}
